<template>
  <div class="middle-design-area" ref="designArea" @drop="handleDrop" @dragover="handleDragOver">
    <div v-for="comp in components"
         :key="comp.id"
         :class="['design-component', comp.name]"
         :style="{ width: comp.width, height: comp.height, backgroundColor: comp.backgroundColor, color: comp.color || '#000' }"
         @click="selectComponent(comp)">
      <input v-if="comp.name === 'Input'" :placeholder="comp.placeholder" :style="{width: comp.width, height: comp.height, color: comp.color}"/>
      <div v-else-if="comp.name === 'Container'" class="container" :style="{width: comp.width, height: comp.height}">
        <p>{{ comp.label }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['selectedComponent'],
  data() {
    return {
      components: []  // 存储设计区域中的组件
    };
  },
  methods: {
    handleDragOver(event) {
      event.preventDefault();  // 允许 drop 事件触发
    },
    handleDrop(event) {
      event.preventDefault();
      const componentData = JSON.parse(event.dataTransfer.getData('component'));
      const designAreaWidth = this.$refs.designArea.offsetWidth;
      const designAreaHeight = this.$refs.designArea.offsetHeight;

      let newComponent = {
        ...componentData,
        id: this.generateId(),
        color: '#000',
      };

      // 限制宽高在设计区域的最大宽高范围内
      newComponent.width = this.adjustSize(newComponent.width, designAreaWidth);
      newComponent.height = this.adjustSize(newComponent.height, designAreaHeight);

      this.components.push(newComponent);
    },
    updateComponent(updatedComp) {
      // 获取设计区域的最大宽度和高度
      const designAreaWidth = this.$refs.designArea.offsetWidth;
      const designAreaHeight = this.$refs.designArea.offsetHeight;

      // 限制组件的宽高不能超过设计区域的宽高
      updatedComp.width = this.adjustSize(updatedComp.width, designAreaWidth);
      updatedComp.height = this.adjustSize(updatedComp.height, designAreaHeight);

      this.$emit('update-component', updatedComp);
    },

    adjustSize(size, maxSize) {
      const sizeValue = parseInt(size, 10);
      return sizeValue > maxSize ? `${maxSize}px` : `${sizeValue}px`;
    },
    generateId() {
      return Math.random().toString(36).substr(2, 12);
    },
    selectComponent(comp) {
      this.$emit('select-component', comp);
    }
  }
};
</script>

<style scoped>
.middle-design-area {
  flex: 1;
  min-height: 500px;
  max-height: 700px;
  max-width: 1000px;
  border: 1px solid #ddd;
  position: relative;
  overflow: auto; /* 添加这个来避免内容撑开 */
}

.design-component {
  position: relative;
  margin: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  text-align: center;
  cursor: pointer;
}

.design-component:hover {
  background-color: #e0e0e0;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
